package app;

import app.auth.AccessManager;
import app.common.Result;
import app.controller.HomeController;
import app.dao.MongoDBConnection;
import app.vo.User;
import io.javalin.Javalin;
import io.javalin.core.util.RouteOverviewPlugin;
import io.javalin.http.Context;
import io.javalin.http.staticfiles.StaticFileConfig;
import org.jetbrains.annotations.NotNull;
import static io.javalin.apibuilder.ApiBuilder.*;

/**
 * Main Application Class.
 * <p>
 * Running this class as regular java application will start the Javalin HTTP
 * Server and our web application.
 *
 * @author Timothy Wiley, 2021. email: timothy.wiley@rmit.edu.au
 * @author Santha Sumanasekara, 2021. email: santha.sumanasekara@rmit.edu.au
 * @author Halil Ali, 2021. email halil.ali@rmit.edu.au
 */
public class App {

   public static final int JAVALIN_PORT = 7000;
   public static final String PUBLIC_DIR = "public/";


   public static void main(String[] args) throws Exception {

      // Establish database connection
      if (MongoDBConnection.getConnection() == null) {
         throw new Exception("Could not establish connection to database");
      }
      // Create our HTTP server and listen in port 7000
      Javalin app = Javalin.create().start(JAVALIN_PORT);

      // capture ctrl-c signal so we can shutdown server safely
      Runtime.getRuntime().addShutdownHook(new Thread(() -> {
         app.stop();
      }));

      // handle shutdown events by closing database and ssh tunnel connections
      app.events(event -> {
         event.serverStopping(() -> {
            System.out.println("server stopping");
         });
         event.serverStopped(() -> {
            System.out.println("server stopped");
            // Close Database connection
            MongoDBConnection.closeConnection();
         });
      });

      configureRoutes(app);
   }

   /**
    * set up each individual page of site
    **/
   public static void configureRoutes(Javalin app) {
      // 登录页面
      app.get("/", HomeController::toHome);
      app.get("/toCenter", HomeController::toCenter);
      app.get("/logout", HomeController::logout);
      app.post("/getHost", HomeController::getHost);
      app.get("/toHost/{id}", HomeController::toHost);
      app.get("/hostInfo/{id}", HomeController::hostInfo);
      app.post("/login", HomeController::login);
      app.post("/addCom", HomeController::addCom);
      app.post("/editCom", HomeController::updateCom);
      app.post("/deleteCom", HomeController::deleteCom);
      app.post("/getMyCom", HomeController::getMyCom);
   }

}
